<?php
namespace app\controller;
use think\facade\Db;

class Index{
    //前端获取表单数据
    public function getFormsData(){
        $forms_code  = request()->param('forms_code');
        if(!isset($forms_code)||empty($forms_code)||$forms_code == 'undefined'){
            return json(['status'=>500,'msg'=>'没有参数code','data'=>'']);
        }
        $forms = Db::table('forms')->where('forms_code',$forms_code)
            ->filter(function ($data){
                $data['forms_content'] = json_decode($data['forms_content'],true);
                return $data;
            })
            ->find();
        if(!empty($forms))
            return json(['status'=>200,'msg'=>'ok','data'=>$forms]);
        else
            return json(['status'=>500,'msg'=>'无效参数code','data'=>'']);
    }
    public function send(){
        //禁止get请求
        if(request()->isGet()){
            return json(['status'=>500,'msg'=>'非法请求']);
        }
        $sendData  = request()->param();

        //取出表单code
        $forms_code = $sendData['forms_code'];
        //取出当前发送验证的字段信息array
        $item = $sendData['item'];
        if(empty($item['bindingMessageId'])){
            return json(['status'=>500,'msg'=>'当前字段没有绑定短信模板！']);
        }
        $formsData = Db::table('forms')->where('forms_code',$forms_code)->find();
        $admin_id = $formsData['admin_id'];
        //以上目的查出短信的账户和密码
        $messages = Db::table('messages')->where('admin_id',$admin_id)->where('messages_id',$item['bindingMessageId'])->find();
        if(empty($messages)){
            return json(['status'=>500,'msg'=>'当前字段绑定短信模板不匹配！']);
        }
        //取出账户和密码
        $userName = $messages['messages_name'];
        $password = $messages['messages_send_pwd'];
        //短信模板计费长度
        $messages_template_length = $messages['messages_template_length'];
        //取出短信模板
        $messages_template =  $messages['messages_template'];

        $message_num =  json_decode(getMessageSum($userName,$password),true);
        if($message_num['balance']<=0 || $message_num['balance'] - $messages_template_length <= 0){
            return json(['status'=>500,'msg'=>'短信余额不足']);
        }
        $forms_id = $sendData['forms_id'];

        $form_title = $sendData['form_title'];
        $submit_phone =  $sendData['phone'];
        if(!preg_match('/^1[3456789]\d{9}$/',$submit_phone)){
            return json([
                'status'=>500,
                'msg'=>$form_title."不正确"
            ]);
        }
        //查询当前号码当天是否发送过验证码
        $send = Db::table('send')
            ->where('send_phone',$submit_phone)
            ->where('send_time',date("Y-m-d"))
            ->find();
        if(empty($send)){//没有发送过验证码，则
            $insert_result = [
                'send_phone'=>$submit_phone,
                'send_num'=>1,
                'send_message_time'=>time(),
                'send_time'=>date('Y-m-d')
            ];
            $field_id = $item['field_id'];
            $key = $field_id.$submit_phone;
            $redis = new \think\cache\driver\Redis();
            $shortVal = rand(1000,9999);
            //5分钟有效
            $redis->set($key,$shortVal,60 * 5);
            // 使用正则表达式匹配并替换占位符
            $pattern = '/{%变量(\d+)%}/';
            $replacement = "{$shortVal}";
            $content = preg_replace($pattern, $replacement, $messages_template);

            $send_dx =  json_decode(shortMessage($userName,$password,$submit_phone,$content),true);
            if($send_dx['code']==0){
                //新增一条记录
                $send_id =  Db::table('send')->insertGetId($insert_result);
                return json(['status'=>200,'msg'=>'短信发送成功']);
            }else{
                return json(['status'=>500,'msg'=>'短信发送失败']);
            }

        }else{//如果当天已发送
            //且数量超过或等于10条，则禁止发送
            if($send['send_num']>=10){
                return json(['status'=>500,'msg'=>'您今天提交过多，明天后再提交']);
            }
            $interval_time = $item['input_time'];//提示间隔时间后再发送(秒)
            //如果还在$this->interval_time秒内，则不可重新发送
            if(time()-$send['send_message_time']<$interval_time){
                $sy_time = $interval_time - (time()-$send['send_message_time']);
                return json(['status'=>500,'msg'=>"发送频繁，请{$sy_time}秒后再试"]);
            }

            $field_id = $item['field_id'];
            $key = $field_id.$submit_phone;
            $redis = new \think\cache\driver\Redis();
            $shortVal = rand(1000,9999);
            //5分钟有效
            $redis->set($key,$shortVal,60 * 5);
            // 使用正则表达式匹配并替换占位符
            $pattern = '/{%变量(\d+)%}/';
            $replacement = "{$shortVal}";
            $content = preg_replace($pattern, $replacement, $messages_template);

            $send_dx =  json_decode(shortMessage($userName,$password,$submit_phone,$content),true);
            if($send_dx['code']==0){
                //否则，次数加 + 1
                Db::table('send')
                    ->where('send_phone',$submit_phone)
                    ->where('send_time',date("Y-m-d"))
                    ->update([
                        'send_message_time'=>time(),
                        'send_num'=>Db::raw('send_num+1'),
                    ]);
                return json(['status'=>200,'msg'=>'短信发送成功']);
            }else{
                return json(['status'=>500,'msg'=>'短信发送失败']);
            }

        }

    }
    public function submitFormsData(){
        $forms  = request()->param();
        $forms_content = $forms['formsData'];
        $forms_code = $forms['forms_code'];
        $forms_id = $forms['forms_id'];
        $where = [
          ['forms_code','=',$forms_code],
          ['forms_id','=',$forms_id],
        ];
        $formsData = Db::table('forms')->where($where)->find();
        if(empty($formsData)){return json(['status'=>500,'msg'=>'表单不存在！']);}
        $time = time();
        if($time<strtotime($formsData['forms_start_time']) || $time>strtotime($formsData['forms_end_time']) ){
            return json(['status'=>500,'msg'=>'不在时间范围内！']);
        }
       $people =  Db::table('submit')
           ->lock(true)
           ->where([
            ['admin_id','=',$formsData['admin_id']],
            ['forms_id','=',$formsData['forms_id']]
        ])->count();
        if( $formsData['forms_people'] > -1){
            if( $people >= $formsData['forms_people']){
                return  json(['status'=>500,'msg'=>'抱歉，人数已报满！']);
            }
        }
        $saveData = [];

        foreach ($forms_content as $k=>$v){
            $form_validate =  $v['form_validate'];
            $form_content = $v['form_content'];
            $form_title = $v['form_title'];
            if(!empty($form_validate)){
                foreach ($form_validate as $validate){
                    //echo "$validate<br>";
                    switch ($validate){
                        case 'require':
                            if(!preg_match('/^\S+/',$form_content)){
                                return json([
                                    'status'=>500,
                                    'msg'=>$form_title."不能为空"
                                ]);
                            }
                            break;
                        case 'unique':
                            $user = Db::table('submit')
                                ->where([
                                    ['admin_id','=',$formsData['admin_id']],
                                    ['forms_id','=',$formsData['forms_id']]
                                ])
                                ->where('submit_content','like','%'.$form_content.'%')->find();
                            if(!empty($user)){
                                return json(['status'=>500,'msg'=>'您已经报名过了']);
                            }
                        break;
                        case 'verification_code'://验证码
                            $field_id = $v['field_id'];
                            $bindingId = $v['bindingId'];
                            if(empty($bindingId)){
                                return json([
                                    'status'=>500,
                                    'msg'=>"没有绑定验证字段"
                                ]);
                            }
                            $result = array_filter($forms_content, function($element)  use  ($bindingId) {
                                return $element['field_id'] == $bindingId;
                            });
                            $result = array_values($result); // 重新索引数组
                            $submit_phone = $result[0]['form_content'];
                            $key = $field_id.$submit_phone;
                            $redis = new \think\cache\driver\Redis();
                            $shortVal = $redis->get($key);
                            if($shortVal != $v['form_content']){
                                return json([
                                    'status'=>500,
                                    'msg'=>$form_title."不正确"
                                ]);
                            }
                            break;
                        case 'mobile':
                            if(!preg_match('/^1[3456789]\d{9}$/',$form_content)){
                                return json([
                                    'status'=>500,
                                    'msg'=>$form_title."不正确"
                                ]);
                            }
                            break;
                        case 'number':
                            if(!preg_match('/^\d+$/',$form_content)){
                                return json([
                                    'status'=>500,
                                    'msg'=>$form_title."只能是数字"
                                ]);
                            }
                            break;
                        case 'idCard':
                            $pattern = '/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/';
                            if(!preg_match($pattern,$form_content)){
                                return json([
                                    'status'=>500,
                                    'msg'=>$form_title."不正确"
                                ]);
                            }
                            break;
                        case 'mail':
                            if(!preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/',$form_content)){
                                return json([
                                    'status'=>500,
                                    'msg'=>$form_title."不正确"
                                ]);
                            }
                            break;
                        case 'alpha':
                            if(!preg_match('/^[A-Za-z]+$/',$form_content)){
                                return json([
                                    'status'=>500,
                                    'msg'=>$form_title."只能是纯字母"
                                ]);
                            }
                            break;
                        case 'alphaNum':
                            if(!preg_match('/^[A-Za-z0-9]+$/',$form_content)){
                                return json([
                                    'status'=>500,
                                    'msg'=>$form_title."只能是字母和数字"
                                ]);
                            }
                            break;
                        case 'chs':
                            if(!preg_match('/^[\x{4e00}-\x{9fa5}\x{9fa6}-\x{9fef}\x{3400}-\x{4db5}\x{20000}-\x{2ebe0}]+$/u',$form_content)){
                                return json([
                                    'status'=>500,
                                    'msg'=>$form_title."只能是汉字"
                                ]);
                            }
                            break;
                        case 'chsAlpha':
                            if(!preg_match('/^[\x{4e00}-\x{9fa5}\x{9fa6}-\x{9fef}\x{3400}-\x{4db5}\x{20000}-\x{2ebe0}a-zA-Z]+$/u',$form_content)){
                                return json([
                                    'status'=>500,
                                    'msg'=>$form_title."只能是汉字和字母"
                                ]);
                            }
                            break;
                    }

                }

            }
//            switch ($formsData['forms_is_require']){
//                case 1:
//                    if(in_array($form_title,['姓名','昵称','名字','称呼'])){
//                        $user = Db::table('submit')->where('submit_content','like','%'.$form_content.'%')->find();
//                        if(!empty($user)){
//                            return json(['status'=>500,'msg'=>'您已经报名过了']);
//                        }
//                    }
//                    break;
//                case 2:
//                    if(in_array($form_title,['手机','手机号','手机号码','联系方式'])){
//                        $user = Db::table('submit')->where('submit_content','like','%'.$form_content.'%')->find();
//                        if(!empty($user)){
//                            return json(['status'=>500,'msg'=>'您已经报名过了']);
//                        }
//                    }
//                    break;
//            }
            $no_submit = array('map','image','button','title','editor','verification','marquee','swiper');
            if(in_array($v['form_type'],$no_submit)){
               unset($v[$k]);
            }else{
                $saveData[] = $v;
            }

        }
        if(empty($saveData)){
            return json(['status'=>500,'msg'=>'没有数据需要提交','data'=>'']);
        }
        $forms = Db::table('submit')->insert([
            'forms_id'=>$forms_id,
            'admin_id'=>$formsData['admin_id'],
            'submit_title'=>$formsData['forms_title'],
            //JSON_UNESCAPED_UNICODE 不转义Unicode字符。
            'submit_content'=>json_encode($saveData,JSON_UNESCAPED_UNICODE),
            'submit_time'=>date("Y-m-d H:i:s")
        ]);
        if(!empty($forms))
            return json(['status'=>200,'msg'=>$formsData['forms_submit_ok_msg'],'data'=>$forms]);
        else
            return json(['status'=>500,'msg'=>$formsData['forms_submit_fail_msg'],'data'=>'']);
    }
}
?>